package cn.yuanqiao.archive.appManager.service.impl;

import cn.yuanqiao.archive.appManager.domain.*;
import cn.yuanqiao.archive.appManager.mapper.*;
import cn.yuanqiao.archive.appManager.service.ITenantCodelistService;
import cn.yuanqiao.archive.chengguojieshou.mapper.YqdaarticulatedMapper;
import cn.yuanqiao.common.enums.DbIdEnum;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.sql.YqDatabaseSQLUtil;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import cn.yuanqiao.common.config.YqDatabaseIdProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * codelistService业务层处理
 *
 * @author yuanqiao
 * @date 2023-06-15
 */
@Service
public class TenantCodelistServiceImpl implements ITenantCodelistService
{
    @Autowired
    private TenantCodeListMapper tenantCodeListMapper;
    @Autowired
    private TenantCodeRuleMapper tenantCodeRuleMapper;
    @Autowired
    private TenantCateMdataListMapper tenantCateMdataListMapper;
    @Autowired
    private TenantFieldsMapper tenantFieldsMapper;
    @Autowired
    private TenantCategoryMapper tenantCategoryMapper;
    @Autowired
    private YqdaarticulatedMapper yqdaarticulatedMapper;
    @Resource
    private YqDatabaseIdProvider yqDatabaseIdProvider;
    @Override
    public String dhOfCheckForDefects(JSONObject json) {
        String tenantCode = SecurityUtils.getTenantCode();
        String categoryId = String.valueOf(json.get("categoryId"));  //，门类ID
        String type = String.valueOf(json.get("datype"));   //类型 0 件 1 卷
        String ruleId = String.valueOf(json.get("ruleId"));  //档号规则id
        String folderId = String.valueOf(json.get("folderId"));  //卷ID  卷内件时必填
        TenantCategory tenantCategory = new TenantCategory();
        TenantCategory tenantCategory1 = tenantCategoryMapper.selectTenantCategoryByID(Long.valueOf(categoryId), tenantCategory.getTableName());
        Integer type1 = tenantCategory1.getType();
        boolean isJnj = false;
        if("0".equals(type) && Integer.valueOf(type)!=type1){
            //卷内件
            isJnj = true;
        }
        String tableName = "0".equals(type)?tenantCategory1.getFileTableName():"1".equals(type)?tenantCategory1.getFolderTableName():"";
        if("".equals(tableName)){
            throw new ServiceException("参数有误！");
        }
        TenantCodeList tenantCodeList = new TenantCodeList();
        List<String> list = null;
        if(isJnj){
            if(StringUtils.isEmpty(folderId) || "null".equals(folderId)) throw new ServiceException("卷ID不能为空");
            list = tenantCodeListMapper.selectNodeValByIdAndType(Long.valueOf(ruleId), "v", tenantCodeList.getTableName());
            List<String> list2 = tenantCodeListMapper.selectNodeValByIdAndType(Long.valueOf(ruleId), "f", tenantCodeList.getTableName());
            list.add(list2.get(0));
        }else{
            list = tenantCodeListMapper.selectNodeValByIdAndType(Long.valueOf(ruleId), "0".equals(type) ? "f" : "1".equals(type) ? "v" : "", tenantCodeList.getTableName());
        }
        String sqlCondition = " a.is_del = 0 and";
        String inputNum = "";
        String whereNum = "";
        String selectField = "";
        boolean isNull = false;
        for(int i=0;i<list.size();i++){
            String key = list.get(i);
            String val = String.valueOf(json.get(key.toUpperCase()));
            if(i==list.size()-1){
                selectField = key;
                if(StringUtils.isNotEmpty(val) && !"null".equals(val)){
                    //sqlCondition2 += " "+selectField+"<="+val+"";
                    inputNum = val;
                }else{
                    isNull = true;
                }
            }else{
                sqlCondition += " a."+key+" = '"+val+"' and";
            }
        }
        if(sqlCondition.endsWith("and")) sqlCondition = sqlCondition.substring(0,sqlCondition.length()-3);
        if(isJnj){
            sqlCondition = " a.id in (select da_id from "+tenantCode+"_yqda_folder where folder_id = "+folderId+") and a.is_del = 0";
        }
        String sql = "select max("+selectField+") as maxNum from "+tableName+" a where"+sqlCondition;
        List<Map<String, Object>> maps = yqdaarticulatedMapper.executeSql(sql);
        //Map<String, Object> map1 = maps.get(0);
        if(maps==null || maps.get(0)==null){
            return "不缺项，最大为0";
        }
        String maxNum = String.valueOf(maps.get(0).get("MAXNUM"));
        if(!"".equals(inputNum)){
            if(Integer.valueOf(inputNum)>Integer.valueOf(maxNum))
                whereNum = maxNum;
            else
                whereNum = inputNum;
        }else{
            whereNum = maxNum;
        }

        String msg = "";
        String finalSql = "select b.id as id from (with x as (select level id from dual connect by level <= "+whereNum+" ) select * from x) b left join " +
                ""+tableName+" a on b.id = a."+selectField+"  and"+sqlCondition+" where a."+selectField+" is null order by id";
        List<Map<String, Object>> maps2 = yqdaarticulatedMapper.executeSql(finalSql);
        if(maps2.size()==0){
            if(Integer.valueOf(whereNum)<Integer.valueOf(maxNum)) msg = "不存在缺项，目前最大为"+maxNum;
            else msg = "不存在缺项，目前最大为"+whereNum;
        }else{
            msg="存在缺项：";
            for(int i=0;i<maps2.size();i++){
                Map<String, Object> map = maps2.get(i);
                Object o = map.get("ID");
                msg+=o+"，";
            }
            if(msg.endsWith("，")) msg = msg.substring(0,msg.length()-1);
        }
        return msg;
    }

    @Override
    public List<Map<String, Object>> getNameByColumn(String fieldName, Long categoryId, String type) {
        String databaseId =  yqDatabaseIdProvider.getDatabaseId();
        String tenantCode = SecurityUtils.getTenantCode();
        String fstr = fieldName;
        fieldName = fieldName.replaceAll(",","','");
        fieldName = "'"+fieldName+"'";

        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(categoryId, new TenantCategory().getTableName());
        String sql = "";
        if(databaseId.equalsIgnoreCase(DbIdEnum.OSCAR.getCode())){
            sql = "select field_caption,field_name,showtype from "+tenantCode+"_mdata_list where group_id = "+tenantCategory.getGroupId()+" " +
                    "and field_name in ("+fieldName.toUpperCase()+") and type = "+type+" order by "+YqDatabaseSQLUtil.YQ_INSTR(fstr.toUpperCase(),"FIELD_NAME")+"";
        }else{
            sql = "select field_caption,field_name,showtype from "+tenantCode+"_mdata_list where group_id = "+tenantCategory.getGroupId()+" " +
                    "and field_name in ("+fieldName+") and type = "+type+" order by field (field_name,"+fieldName+")";
        }
        List<Map<String, Object>> maps = yqdaarticulatedMapper.executeSql(sql);
        /*Map<String, Object> hashMap = new HashMap<>();
        if(maps.size()!=0 && maps!=null){
            for(int i=0;i<maps.size();i++){
                Map<String, Object> map = maps.get(i);
                String field_caption = String.valueOf(map.get("FIELD_CAPTION"));
                String field_name = String.valueOf(map.get("FIELD_NAME"));
                hashMap.put(field_name,field_caption);
            }
        }*/
        return maps;
    }

    /**
     * 查询codelist
     *
     * @param Id codelist主键
     * @return codelist
     */
    @Override
    public TenantCodeList selectYqdaCodelistModelById(Long Id)
    {
        return tenantCodeListMapper.selectYqdaCodelistModelById(Id);
    }

    /**
     * 查询codelist列表
     *
     * @param yqdaCodelistModel codelist
     * @return codelist
     */
    @Override
    public List<TenantCodeList> selectYqdaCodelistModelList(TenantCodeList yqdaCodelistModel)
    {
        return tenantCodeListMapper.selectYqdaCodelistModelList(yqdaCodelistModel);
    }

    /**
     * 新增codelist
     *
     * @param  json
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertYqdaCodelistModel(JSONObject json)
    {
        LoginUser user = SecurityUtils.getLoginUser();
        if(user == null){
            user = new LoginUser();
            user.setUserId(1L);
        }
        int type=json.getInteger("type");
        Long Id = json.getLong("id");
        JSONArray ziduanarr = json.getJSONArray("ziduanarr");
        JSONArray fuhaoarr = json.getJSONArray("fuhaoarr");
        JSONArray bulingarr = json.getJSONArray("bulingarr");
        TenantCodeRule yqdaCoderuleModel=new TenantCodeRule();
        yqdaCoderuleModel.setId(Id);
        String order = json.getString("order");
        if(StringUtils.isNotEmpty(order)){
            yqdaCoderuleModel.setOrderStr(json.getString("order").replace("$"," "));
        }
        yqdaCoderuleModel.seteColumnname("ARCHIVE_NO");
        for (int i = 0; i < ziduanarr.size(); i++) {
            TenantCodeList yqdaCodelistModel=new TenantCodeList();
            yqdaCodelistModel.setArchivalcodeRuleId(Id);
            yqdaCodelistModel.setType("著录项值");
            yqdaCodelistModel.setNodeValue(String.valueOf(ziduanarr.get(i)));
            if (i==ziduanarr.size()-1){
                String s = String.valueOf(bulingarr.get(i));
                //String s = (String) bulingarr.get(i);
                if(StringUtils.isNotEmpty(s)) yqdaCodelistModel.setLen(Integer.parseInt(String.valueOf(bulingarr.get(i))));
                else yqdaCodelistModel.setLen(0);
            }else{
                yqdaCodelistModel.setLen(0);
            }
            yqdaCodelistModel.setOrderNo(2*i+1);
            yqdaCodelistModel.setCreator(user.getUsername());
            yqdaCodelistModel.setCreatorId(user.getUserId());
            yqdaCodelistModel.setCreateTime(DateUtils.getNowDate());
            yqdaCodelistModel.setVFETYPE(0==type?"f":"v");
            tenantCodeListMapper.insertTenantCodeList(yqdaCodelistModel);
            if (i!=ziduanarr.size()-1){
                TenantCodeList yqdaCodelistModel1=new TenantCodeList();
                yqdaCodelistModel1.setArchivalcodeRuleId(Id);
                yqdaCodelistModel1.setType("固定值");
                if(fuhaoarr.size()!=0){
                    yqdaCodelistModel1.setNodeValue(String.valueOf(fuhaoarr.get(i)));
                }
                yqdaCodelistModel1.setLen(0);
                yqdaCodelistModel1.setOrderNo(2*(i+1));
                yqdaCodelistModel1.setCreator(user.getUsername());
                yqdaCodelistModel1.setCreatorId(user.getUserId());
                yqdaCodelistModel1.setCreateTime(DateUtils.getNowDate());
                yqdaCodelistModel1.setVFETYPE(0==type?"f":"v");
                tenantCodeListMapper.insertTenantCodeList(yqdaCodelistModel1);
            }
        }
        TenantCodeList yqdaCodelistModel=new TenantCodeList();
        yqdaCodelistModel.setArchivalcodeRuleId(Id);
        yqdaCodelistModel.setType("固定值");
        yqdaCodelistModel.setNodeValue(json.getString("filelianjie"));
        yqdaCodelistModel.setLen(0);
        yqdaCodelistModel.setOrderNo(0);
        yqdaCodelistModel.setCreator(user.getUsername());
        yqdaCodelistModel.setCreatorId(user.getUserId());
        yqdaCodelistModel.setCreateTime(DateUtils.getNowDate());
        yqdaCodelistModel.setVFETYPE("e");
        tenantCodeListMapper.insertTenantCodeList(yqdaCodelistModel);
        if (0==type){//组件方式
            yqdaCoderuleModel.setfColumnname(json.getString("columnname"));
        }else{//组卷 或 项目
            yqdaCoderuleModel.setvColumnname(json.getString("columnname"));
            yqdaCoderuleModel.setfColumnname(json.getString("jiancunchuziduan"));
            TenantCodeList yqdaCodelistModel1=new TenantCodeList();
            yqdaCodelistModel1.setArchivalcodeRuleId(Id);
            yqdaCodelistModel1.setType("著录项值");
            yqdaCodelistModel1.setNodeValue(json.getString("jianziduan"));
            yqdaCodelistModel1.setLen(json.getInteger("jianbuling"));
            yqdaCodelistModel1.setOrderNo(1);
            yqdaCodelistModel1.setCreator(user.getUsername());
            yqdaCodelistModel1.setCreatorId(user.getUserId());
            yqdaCodelistModel1.setCreateTime(DateUtils.getNowDate());
            yqdaCodelistModel1.setVFETYPE("f");
            tenantCodeListMapper.insertTenantCodeList(yqdaCodelistModel1);
            TenantCodeList yqdaCodelistModel2=new TenantCodeList();
            yqdaCodelistModel2.setArchivalcodeRuleId(Id);
            yqdaCodelistModel2.setType("固定值");
            yqdaCodelistModel2.setNodeValue(json.getString("jianlianjie"));
            yqdaCodelistModel2.setLen(0);
            yqdaCodelistModel2.setOrderNo(0);
            yqdaCodelistModel2.setCreator(user.getUsername());
            yqdaCodelistModel2.setCreatorId(user.getUserId());
            yqdaCodelistModel2.setCreateTime(DateUtils.getNowDate());
            yqdaCodelistModel2.setVFETYPE("f");
            tenantCodeListMapper.insertTenantCodeList(yqdaCodelistModel2);
        }
        return tenantCodeRuleMapper.updateYqdaCoderuleModel(yqdaCoderuleModel);
    }

    /**
     * 修改codelist
     *
     * @param json codelist
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateYqdaCodelistModel(JSONObject json)
    {
        Long id=json.getLong("id");
        String order= json.getString("order");
        TenantCodeRule yqdaCoderuleModel=new TenantCodeRule();
        yqdaCoderuleModel.setId(id);
        yqdaCoderuleModel.setOrderStr(order);
        tenantCodeRuleMapper.updateYqdaCoderuleModel(yqdaCoderuleModel);
        deleteYqdaCodelistModelByRuleId(id);
        return insertYqdaCodelistModel(json);
    }


    private void deleteYqdaCodelistModelByRuleId(Long id) {
        TenantCodeList tenantCodeList = new TenantCodeList();
        String tableName = tenantCodeList.getTableName();
        int i= tenantCodeListMapper.deleteYqdaCodelistModelByRuleId(id,tableName);
    }

    /**
     * 批量删除codelist
     *
     * @param Ids 需要删除的codelist主键
     * @return 结果
     */
    @Override
    public int deleteYqdaCodelistModelByIds(Long[] Ids)
    {
        return tenantCodeListMapper.deleteYqdaCodelistModelByIds(Ids);
    }

    /**
     * 删除codelist信息
     *
     * @param Id codelist主键
     * @return 结果
     */
    @Override
    public int deleteYqdaCodelistModelById(Long Id)
    {
        return tenantCodeListMapper.deleteYqdaCodelistModelById(Id);
    }

    @Override
    public JSONObject getdetail(String type,Long archivalcodeRuleId) {
        JSONObject json=new JSONObject();
        TenantCodeList yqdaCodelistModel=new TenantCodeList();
        yqdaCodelistModel.setArchivalcodeRuleId(archivalcodeRuleId);
        List<TenantCodeList> yqdaCodelistModels = tenantCodeListMapper.selectYqdaCodelistModelList(yqdaCodelistModel);
        List<String> ziduanarr=new ArrayList<>();
        List<String> fuhaoarr=new ArrayList<>();
        List<String> bulingarr=new ArrayList<>();
        for (int i = 0; i < yqdaCodelistModels.size(); i++) {
            if(yqdaCodelistModels.get(i).getVFETYPE().equals(type)&&"著录项值".equals(yqdaCodelistModels.get(i).getType())){//件
                ziduanarr.add(yqdaCodelistModels.get(i).getNodeValue());
                bulingarr.add(String.valueOf(yqdaCodelistModels.get(i).getLen()));
            }else if(yqdaCodelistModels.get(i).getVFETYPE().equals(type)&&"固定值".equals(yqdaCodelistModels.get(i).getType())){ //卷 或 项目
                fuhaoarr.add(yqdaCodelistModels.get(i).getNodeValue());
            }else if("e".equals(yqdaCodelistModels.get(i).getVFETYPE())){
                json.put("filelianjie",yqdaCodelistModels.get(i).getNodeValue());
            }else{
                if("著录项值".equals(yqdaCodelistModels.get(i).getType())){
                    json.put("jianziduan",yqdaCodelistModels.get(i).getNodeValue());
                    json.put("jianbuling",yqdaCodelistModels.get(i).getLen());
                }else{
                    json.put("jianlianjie",yqdaCodelistModels.get(i).getNodeValue());
                }
            }
        }
        json.put("ziduanarr",ziduanarr);
        json.put("fuhaoarr",fuhaoarr);
        json.put("bulingarr",bulingarr);
        TenantCodeRule tenantCodeRule = new TenantCodeRule();
        TenantCodeRule yqdaCoderuleModel = tenantCodeRuleMapper.selectYqdaCoderuleModelById(archivalcodeRuleId,tenantCodeRule.getTableName());
        json.put("columnname","f".equals(type)?yqdaCoderuleModel.getfColumnname():yqdaCoderuleModel.getvColumnname());
        json.put("jiancunchuziduan",yqdaCoderuleModel.getfColumnname());
        json.put("order",yqdaCoderuleModel.getOrderStr());
        json.put("filecunchuziduan",yqdaCoderuleModel.geteColumnname());
        return json;
    }

    @Override
    public List<TenantMdataList> getjiancunchuziduan(String categoryId) {
        TenantMdataList tenantMdataList = new TenantMdataList();
        TenantCategory tenantCategory = new TenantCategory();
        return tenantCateMdataListMapper.getjiancunchuziduan(categoryId,tenantMdataList.getTableName(),tenantCategory.getTableName());
    }
    public List<TenantMdataList> getcodecolumnname(String categoryId,Integer type) {
        TenantMdataList tenantMdataList = new TenantMdataList();
        TenantCategory tenantCategory = new TenantCategory();
        return tenantCateMdataListMapper.getcodecolumnname(categoryId,tenantMdataList.getTableName(),tenantCategory.getTableName(),type);
    }
    public List<TenantMdataList> getjianziduanselect(String categoryId) {
        TenantMdataList tenantMdataList = new TenantMdataList();
        TenantCategory tenantCategory = new TenantCategory();
        return tenantCateMdataListMapper.getjianziduanselect(categoryId,tenantMdataList.getTableName(),tenantCategory.getTableName());
    }
    public List<TenantMdataList> getselect(String categoryId,Integer type) {
        TenantMdataList tenantMdataList = new TenantMdataList();
        TenantCategory tenantCategory = new TenantCategory();
        TenantFields tenantFields = new TenantFields();
        return tenantCateMdataListMapper.getselect(categoryId,tenantMdataList.getTableName(),tenantCategory.getTableName(),tenantFields.getTableName(),type);
    }
    public List<TenantMdataList> getpaixuselect(String categoryId,Integer type) {
        TenantMdataList tenantMdataList = new TenantMdataList();
        TenantCategory tenantCategory = new TenantCategory();
        return tenantCateMdataListMapper.getpaixuselect(categoryId,tenantMdataList.getTableName(),tenantCategory.getTableName(),type);
    }
    public List<Map<String,Object>> getorderright(Long id,String type) {
        TenantCodeRule tenantCodeRule = new TenantCodeRule();
        ArrayList<Map<String,Object>> list = new ArrayList<>();
        String getorderright = tenantCateMdataListMapper.getorderright(id, tenantCodeRule.getTableName());
        if(StringUtils.isNotEmpty(getorderright)){
            TenantFields tenantFields = new TenantFields();
            String[] split = getorderright.split(",");
            for(int i=0;i<split.length;i++){
                HashMap<String, Object> map = new HashMap<>();
                String s = split[i];
                String[] split1 = s.split("\\ ");
                map.put("fieldName",split1[0]);
                tenantFields.setType(type);
                tenantFields.setFieldName(split1[0]);
                List<TenantFields> tenantFields1 = tenantFieldsMapper.selectTenantFieldsList(tenantFields);
                map.put("fieldCaption",tenantFields1.get(0).getFieldCaption());
                map.put("order",split1[1]);
                list.add(map);
            }
        }
        return list;
    }
    public List<TenantMdataList> getorderleft(Long id,String categoryId,Integer type) {
        TenantCodeRule tenantCodeRule = new TenantCodeRule();
        TenantMdataList tenantMdataList = new TenantMdataList();
        TenantCategory tenantCategory = new TenantCategory();
        String getorderright = tenantCateMdataListMapper.getorderright(id, tenantCodeRule.getTableName());
        String replace = null;
        if(StringUtils.isNotEmpty(getorderright)){
            replace = getorderright.replace("asc", "").replace("desc", "").replace(",", "','").replace(" ", "");
            replace = "'"+replace+"'";
        }
        return tenantCateMdataListMapper.getorderleft(categoryId,type,replace,tenantMdataList.getTableName(),tenantCategory.getTableName());
    }
}
